
class ImageWin{
    downloadImage(url) {
        // 发送 HTTP GET 请求获取网页内容
        fetch(url)
            .then(response => response.text())
            .then(html => {
                // 使用选择器选取指定位置的图片元素
                let selector = "";
                if (/bus/.test(url)){
                    selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
                }else if (/javdb/.test(url)){
                    selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
                }

                const imgElement = document.querySelector(selector);
                if (imgElement) {
                    // 获取图片的 src 属性值
                    let imageUrl = imgElement.src;


                } else {
                    console.error('未能找到指定位置的图片元素。');
                }
            })
            .catch(error => console.error('爬取或下载图片时发生错误:', error));
    }

    checkLocalFileExists(fileName) {
        // 调用本地文件系统的 API 来检查文件是否存在
        const fileExists = window.localStorage.getItem(fileName) !== null;

        return fileExists;
    }

    //* ******************************************************************************* *
    addPreloadImage() {
        let mm = document.getElementsByClassName("main")[0];
        if (mm) {
            /* 按钮面板 */
            let preloadDiv = document.createElement("div");
            preloadDiv.id = "preload-image";


            /* 大预览图 */
            let img = document.createElement("image");
            img.style.width = "640px";
            img.style.height = "480px";
            img.src = "https://www.fanbus.cfd/pics/cover/7zdk_b.jpg";
            img.title = "超絶美女教師を全裸羞恥で興奮させOKさせろ";

            preloadDiv.appendChild(img);

            mm.appendChild(preloadDiv);
        }
    }

    addSelectEvent() {
        var elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
        for (var i = 0; i < elements.length; i++) {
            var customValue = elements[i].getAttribute("role"); // 获取每个元素的自定义属性值
            if (customValue == "listitem") {
                elements[i].addEventListener("click", function(event) {
                    // 在这里编写处理选择事件的代码
                    let listItem = event.currentTarget
                    let url = listItem.getElementsByClassName("url")[0];
                    console.log(url.innerText); // 输出自定义属性值到控制台
                });

                // let url = elements[i].getElementsByClassName("url")[0];
                // console.log(url.innerText); // 输出自定义属性值到控制台
            }
        }
    }

    async fetchAndExtractData(url, selector) {
        try {
            // 使用fetch API发送跨域请求
            const response = await fetch(url);
            const text = await response.text();

            // 使用DOMParser解析HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(text, 'text/html');

            // 使用querySelector选择元素并提取值
            const element = doc.querySelector(selector);
            const value = element ? element.src : null;

            return value;
        } catch (error) {
            console.error('爬取或下载图片时发生错误:', error);
            return null;
        }
    }

    async fetchAndExtractData2(url, selector) {
        try {
            // 发送跨域请求
            const response = await axios.get(url);
            const html = response.data;

            // 解析HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            // 选择元素并提取值
            const element = doc.querySelector(selector);
            const value = element ? element.textContent : null;

            return value;
        } catch (error) {
            console.error('Error fetching and extracting data:', error);
            return null;
        }
    }
    showImageWindow(codeUrl){
        // 发送 HTTP GET 请求获取网页内容
        // fetch(codeUrl)
        //     .then(response => response.text())
        //     .then(html => {
        //         // 使用选择器选取指定位置的图片元素
        //         let selector = "";
        //         if (/bus/.test(codeUrl)){
        //             selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
        //         }else if (/javdb/.test(codeUrl)){
        //             selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
        //         }
        //
        //         const imgElement = document.querySelector(selector);
        //         if (imgElement) {
        //             // 获取图片的 src 属性值
        //             let imageUrl = imgElement.src;
        //
        //             let floatingImage = document.getElementById("floatingImage");
        //             floatingImage.src = imageUrl;
        //
        //             let floatingWindow = document.getElementById("image-window");
        //             floatingWindow.style.display = "block";
        //
        //         } else {
        //             console.error('未能找到指定位置的图片元素。');
        //         }
        //     })
        //     .catch(error => console.error('爬取或下载图片时发生错误:', error));

        let selector = "";
        if (/bus/.test(codeUrl)){
            selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
        }else if (/javdb/.test(codeUrl)){
            selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
        }


        fetchAndExtractData2(codeUrl, selector)
            .then(imageUrl=>{
                let floatingImage = document.getElementById("floatingImage");
                floatingImage.src = imageUrl;

                let floatingWindow = document.getElementById("image-window");
                floatingWindow.style.display = "block";
            });

    }
}

class Data115 {
    //* ******************************************************************************* *
    /**
     * 查询115网盘是否拥有番号
     * @param {string} javId 番号
     * @param {Function} callback 回调函数
     */
    static search115Data(javId, callback) {
        //异步请求搜索115番号 //115查询
        let javId2 = javId.replace(/(-)/g, ""); //把番号-去除，例如ABC-123 =》 ABC123
        let javId3 = javId.replace(/(-)/g, "00"); //把番号-替换为00，例如CCVR-065 =》 CCVR00065
        let javId4 = javId.replace(/(-)/g, "-0"); //把番号-替换为-0，例如DSVR-584 =》 DSVR-0584
        console.log("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`)

        //保存查询关键词参数
        //GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

        let url = `https://webapi.115.com/files/search?search_value=${javId}%20${javId2}%20${javId3}%20${javId4}&format=json`;
        // 使用 fetch 发送 GET 请求
        fetch(url, {
            method: 'GET',
            headers: {
                "Cache-Control": "no-cache",
            }
        })
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                    callback(false, null, null);
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                if (resultJson.count > 0) {
                    let pickcode = '';
                    let cid = '';
                    let isRecord = false
                    let isFavorite = false
                    let reg = new RegExp(GM_getValue("115_search_var"), "gi");
                    for (let i = 0; i < resultJson.data.length; i++) {
                        let row = resultJson.data[i];
                        if (row.play_long && (row.n.search(reg) >= 0)) { //iv vdi ico play_long
                            pickcode = row.pc;
                            cid = row.cid

                            if (row.m == "1"){
                                isFavorite = true;
                            }

                            var flList = row.fl;
                            if (flList){
                                for (let j = 0; j < flList.length; j++) {
                                    var flagName = flList[j].name;
                                    if (flagName == "A▓▓" || flagName == "A██"){
                                        isRecord = true;
                                        break;
                                    }
                                }
                            }

                            callback(true, `https://115vod.com/?pickcode=${pickcode}`, pickcode, `https://115.com/?cid=${cid}&offset=0&mode=wangpan`, isRecord, isFavorite);
                            return;
                        }
                    }
                }
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('There was a problem with your fetch operation:', error);
                callback(false, null, null);
            });

    }

    static jumpJDB(avcode){
        let jdbUrl = "https://javdb458.com/search?q=" + avcode + "&f=all";

        Data115.parseJdbUrl(jdbUrl);

        // var newWindow = window.open(jdbUrl, '_blank'); // 在新标签页中打开URL
        // // 可选：检查窗口是否成功打开
        // if (!newWindow) {
        //     // 窗口可能被浏览器阻止了
        //     alert('请允许浏览器打开新窗口或标签页。');
        // }
    }
	
	static jumpSearchUrl(avcode){
		let jdbUrl = "https://javdb458.com/search?q=" + avcode + "&f=all&jump=auto";

		var newWindow = window.open(jdbUrl, '_blank'); // 在新标签页中打开URL
		// 可选：检查窗口是否成功打开
		if (!newWindow) {
			// 窗口可能被浏览器阻止了
			alert('请允许浏览器打开新窗口或标签页。');
		}
	}

    static parseCode(str){
        // let str = "AB12345-67890"; // 示例字符串，注意它不完全符合你的模式
        let pattern = /[a-zA-Z]{2,5}-?[0-9]{2,5}/; // 定义正则表达式

        let str2 = str.replace(".HD", "").replace(".FHD", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/, '');
        let matchResult = str2.match(pattern);

        if (matchResult) {
            // 如果匹配成功，matchResult[0]将包含完整的匹配项
            console.log(matchResult[0]); // 输出匹配到的字符串
            return matchResult[0];

        } else {
            console.log("没有匹配到字符串");
            return null;
        }
    }

    static getDomainFromUrl(url) {
        // 创建一个新的URL对象
        const urlObj = new URL(url);
        // 使用hostname属性获取域名
        return urlObj.hostname;
    }

    static parseJdbUrl(targetUrl){
        let domain = Data115.getDomainFromUrl(targetUrl);

        fetch(targetUrl) // 请求用户指定的页面
            .then(response => response.text())
            .then(html => {
                console.log(html);
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const movieList = doc.getElementsByClassName('movie-list');
                if (movieList.length > 0) {
                    const firstElement = movieList[0];
                    const firstLink = firstElement.querySelector('a');
                    if (firstLink) {
                        const href = firstLink.getAttribute('href');

                        var fullUrl = "http://" + domain + href;

                        var newWindow = window.open(fullUrl, '_blank'); // 在新标签页中打开URL
                        if (!newWindow) {
                            // 窗口可能被浏览器阻止了
                            alert('请允许浏览器打开新窗口或标签页。');
                        }
                    }
                }
            })
            .catch(err => console.error('Error fetching and parsing HTML', err));
    }

    static removeFirstTextNode(element) {
        // 检查元素是否存在
        if (!element) return;

        // 遍历子节点
        for (let i = 0; i < element.childNodes.length; i++) {
            // 检查节点是否是文本节点
            if (element.childNodes[i].nodeType === 3) {
                // 如果是，则移除它
                element.removeChild(element.childNodes[i]);
                // 由于移除了节点，列表的长度已经改变，我们可以停止循环
                break;
            }
        }
    }

    static formatCode(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "-" + numbers[0];
            }
        }

        return newCode;
    }

    static formatCodeForNone(code) {
        let newCode = code;
        let numbers = code.match(/\d+/g);
        let chars = code.match(/[a-zA-Z]+/g);

        if (numbers && chars) {
            newCode = chars[0] + "%20" + numbers[0];
        }

        return newCode;
    }

}

class Logitem{
    static logItemList(){
        let elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
        let logText = "";
        for (var i = 0; i < elements.length; i++) {
            var customValue = elements[i].getAttribute("role"); // 获取每个元素的自定义属性值
            if (customValue == "listitem") {
                let url = elements[i].getElementsByClassName("url")[0];
                // console.log(url.innerText); // 输出自定义属性值到控制台
                logText = logText + url.innerText + "\n";
            }
        }
        console.log(logText);
        logText = logText + "\n"

        let addrDiv = document.getElementById("addr-list");
		if(addrDiv){
			let allText = addrDiv.innerText + logText;
			addrDiv.innerText = allText;
		}
        
    }

    static logSelItem() {
        var selItems = list.selectedItems;
        let logText = "";

        for (let index = 0; index < selItems.length; index++) {
            var bookmarkNode = selItems[index];

            var itemTitle = bookmarkNode.title;
            var itemUrl = bookmarkNode.url;

            var codeText = Data115.parseCode(itemTitle);
            if (codeText){
                logText = logText + itemUrl + "\n";
            }
        }

        console.log(logText);
        logText = logText + "\n"

        let addrDiv = document.getElementById("addr-list");
		if(addrDiv){
			let allText = addrDiv.innerText + logText;
			addrDiv.innerText = allText;
		}
        
    }

    static clearAddrList(){
        let addrDiv = document.getElementById("addr-list");
		if(addrDiv){
			addrDiv.innerText = "";
		}
    }
	
}

class PlayFlag{

    //static flagMap = new Map;

    static async handleFolderSelection() {
        try {
            // 请求用户选择一个目录
            const directoryHandle = await window.showDirectoryPicker();

            if (!directoryHandle) {
                console.log('User did not select a directory.');
                return;
            }

            //PlayFlag.flagMap.clear();
            localStorage.clear();


            // 使用 values() 迭代器遍历目录中的文件和子目录
            for await (const entry of directoryHandle.values()) {
                if (entry.kind === 'file') {
                    // 处理文件
                    //console.log('File:', entry.name);
                    // 你也可以获取文件的 FileSystemFileHandle 来进一步操作文件
                    // const fileHandle = await entry.getFileHandle();
                    const filename = entry.name;

                    // 是否为part
                    const isPart = /(_part2)|(_part3)+/g.test(filename);

                    const filename2 = filename.replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
                    // 使用正则表达式匹配文件名
                    const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
                    const match = filename2.match(regex);

                    // 如果找到匹配项，将其作为键存入 Map
                    // 注意：这里我们假设每个匹配的文件名都是唯一的，或者我们只关心第一个匹配项
                    if (match && match[0]) {
                        var avcode = match[0].toUpperCase();
                        //PlayFlag.flagMap.set(avcode, filename); // 或者你可以存储其他与匹配项相关的数据
                        let fileFlag = await PlayFlag.parseFileContent(entry);

                        if (isPart){
                            let newFlag = localStorage.getItem(avcode) + fileFlag;
                            localStorage.setItem(avcode, newFlag);
                        }else {
                            localStorage.setItem(avcode, fileFlag);
                        }

                    }else {
                        console.log('not match file:', entry.name);
                    }

                } else if (entry.kind === 'directory') {
                    // 处理子目录
                    console.log('Directory:', entry.name);
                    // 你可以递归地调用这个函数来处理子目录
                    // 注意：这里需要小心递归深度，避免无限循环或堆栈溢出
                }
            }

            alert("读取目录完成！");
        } catch (error) {
            console.error('Error accessing the directory:', error);
            alert("读取目录error: " + error);
        }
    }

    static async parseFileContent(fileHandle){
        const file = await fileHandle.getFile();
        const fileContent = await file.text();
        const lines = fileContent.split('\n'); // 按行分割文件内容

        const resultMap = new Map();

        // 检查文件是否有足够的行数
        if (lines.length >= 23) {
            const specificLines = lines.slice(20, 24); // 获取第20到23行（索引从0开始，所以要slice(19, 23)）

            // 遍历这4行，每行按逗号分割并存储到resultArray中
            for (const line of specificLines) {
                //const values = line.split(',');
                for(const value of line.split(',')){
                    if (value > 0 && !resultMap.has(value)){
                        let str = PlayFlag.getFlagPointStr(value);
                        resultMap.set(value, str);
                    }
                }
            }
        }

        let zi = "■■■";
        let ziValues = Array.from(resultMap.values());
        if (ziValues.length > 0){
            zi = '[';
            for (let item of ziValues){
                zi += item;
            }
            zi += ']';
        }

        return zi;
    }

    static getFlagPointStr(itemType){
        let str = "";
        let strGao = ""

        let gaoType = Math.floor(itemType / 100);
        let diType = itemType % 100;

        if (gaoType == 31){
            strGao = "3";
        }else if (gaoType == 32){
            strGao = "2";
        }else if (gaoType == 33){
            strGao = "N"

        }else if (gaoType == 41){
            strGao = "4";
        }else if (gaoType == 42){
            strGao = "6";
        }else if (gaoType == 43) {
            strGao = "M";
        }

        if (diType == 71){
            str = "沙";
        }else if (diType == 72){
            str = "钞";
        }else if (diType == 73){
            str = "桌"

        }else if (diType == 81){
            str = "床";
        }else if (diType == 82){
            str = "麻";
        }else if (diType == 83){
            str = "旦";

        }else if (diType == 91){
            str = "浴";
        }else if (diType == 92){
            str = "厕";
        }else if (diType == 93){
            str = "火";

        }else if (diType == 61){
            str = "丛";
        }else if (diType == 62){
            str = "内";
        }else if (diType == 63) {
            str = "野";
        }

        return strGao + str;
    }

    static isNonEmptyString(str) {
        // 首先检查str是否为字符串类型
        if (!str){
            return false;
        }

        if (typeof str !== 'string') {
            return false; // 如果不是字符串，直接返回false
        }

        // 使用trim()方法去除字符串两端的空白字符，然后检查长度
        return str.trim().length > 0;
    }

    static findFlag(code){
        if (!PlayFlag.isNonEmptyString(code)){
            return null;
        }

        var avcode = code.toUpperCase();
        var avcode2 = avcode.replace("-", "");

        // if (PlayFlag.flagMap.size <= 0){
        //     console.error("PlayFlag.flagMap.size error!");
        //
        //     return false;
        // }

        //var fname = PlayFlag.flagMap.get(avcode);
        var fname = localStorage.getItem(avcode);
        if (fname){
            return fname;
        }

        fname = localStorage.getItem(avcode2);
        if (!fname){
            return fname;
        }

        console.error("fname error!");
        return null;
    }
}

class BookmarkTools{
    static removeStringAndAfter(str, searchStr) {
        // 查找searchStr在str中的位置
        const index = str.indexOf(searchStr);

        // 如果找到了searchStr
        if (index !== -1) {
            // 使用slice从0到searchStr的位置（不包括searchStr）切片字符串
            return str.slice(0, index);
        }

        // 如果没有找到searchStr，返回原始字符串
        return str;
    }

    static renameSelItem() {
        var selItems = list.selectedItems;

        for (let index = 0; index < selItems.length; index++) {
            var bookmarkNode = selItems[index];

            var oldTitle = bookmarkNode.title;
            var newTitle = BookmarkTools.removeStringAndAfter(oldTitle, '_115');

            if (newTitle.length < oldTitle.length){
                chrome.bookmarks.update(bookmarkNode.id, {
                    title: newTitle,
                });
            }
        }
    }
	
	static resetBus(oldUrl){
		var newUrl = null;
		
		// 查找searchStr在str中的位置
        const index = oldUrl.indexOf('bus');

        // 如果找到了searchStr
        if (index !== -1) {
			if (!oldUrl.includes('https://www.busfan.shop/')) {
				const regex = /https:\/\/www\.[a-z]{2,10}\.[a-z]{2,10}\//;
				newUrl = oldUrl.replace(regex, 'https://www.busfan.shop/');
			}
        }

		return newUrl;
	}
	
	static resetUrlSelItem() {
        var selItems = list.selectedItems;

        for (let index = 0; index < selItems.length; index++) {
            var bookmarkNode = selItems[index];

            
            var newUrl = BookmarkTools.resetBus(bookmarkNode.url);

            if (newUrl){
                chrome.bookmarks.update(bookmarkNode.id, {
                    url: newUrl,
                });
            }
        }
    }
}

function addItemListButton(){
    // let sss = document.createElement("script");
    // sss.src = "https://unpkg.com/axios/dist/axios.min.js";
    // document.head.appendChild(sss);

    let elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
    for (var i = 0; i < elements.length; i++) {
        const item = elements[i];

        var customValue = item.getAttribute("role"); // 获取每个元素的自定义属性值
        if (customValue == "listitem") {
            let labelEle = item.getElementsByClassName("label")[0];
            let labelText = labelEle.textContent
            const codeText = Data115.parseCode(labelText);
            if (!codeText) continue;

            let urlEle = item.getElementsByClassName("url")[0];
            const codeUrl = urlEle.innerText;

            let domainEle = item.getElementsByClassName("domain")[0];
            Data115.removeFirstTextNode(domainEle);
            domainEle.style = `
                -webkit-padding-end: 5px;
                right: 5px;
                width: 160px;
            `;

            labelEle.style.paddingRight = '120px';

            let delEle = item.getElementsByClassName('del')[0];
            delEle.style.display = 'none';

            item.style = `
                -webkit-padding-start: 5px;
                padding-right: 5px;
            `;

            let jdbBtn = item.getElementsByClassName("jdb-button")[0];
            if (!jdbBtn) {
                jdbBtn = document.createElement("button");
                jdbBtn.className = "jdb-button";
                jdbBtn.style.color = "#4242c7"
                jdbBtn.style.marginRight = "5px";
                let btnName = PlayFlag.findFlag(codeText);
                if (PlayFlag.isNonEmptyString(btnName)){
                    jdbBtn.textContent = btnName
                }else {
                    jdbBtn.textContent = "----";
                }

                jdbBtn.addEventListener("click", function (event) {
                    let codeText2 = Data115.formatCode(codeText);
                    // Data115.jumpJDB(codeText2);
					Data115.jumpSearchUrl(codeText2);
                });

                domainEle.appendChild(jdbBtn);
            }

            // // video显示和隐藏按钮
            // let videoBtn = item.getElementsByClassName("video-button")[0];
            // if (!videoBtn) {
            //     videoBtn = document.createElement("button");
            //     videoBtn.className = "video-button";
            //     videoBtn.style.color = "#9e9e9e"
            //     videoBtn.style.marginRight = "10px";
            //     videoBtn.textContent = "预览";
            //
            //     videoBtn.addEventListener("click", function (event) {
            //         // 可选：阻止默认行为（如果有的话）
            //         var video = item.querySelector('video');
            //         if (video.style.display == "none"){
            //             video.style.display = 'block';
            //
            //             if (!video['src']) {
            //                 videoBtn.style.color = "#4242c7"
            //                 video.src = video.dataset.src;
            //             }
            //         }else {
            //             video.style.display = 'none';
            //         }
            //     });
            //
            //     domainEle.appendChild(videoBtn);
            // }

            let playBtn = item.getElementsByClassName("play-button")[0];
            if (!playBtn) {
                let mulu = item.getElementsByClassName('tree-label')[0];

                playBtn = document.createElement("button");
                playBtn.className = "play-button";
                playBtn.style.color = "#45b71d"
                playBtn.style.marginLeft = "5px";
                if (mulu) {
                    playBtn.textContent = mulu.textContent;
                    domainEle.removeChild(mulu);
                }else {
                    playBtn.textContent = "播放";
                }

                playBtn.addEventListener("click", function (event) {
                    // 跳转115播放
                    if (codeText){
                        let codeText2 = Data115.formatCodeForNone(codeText);
                        let url = `https://webapi.115.com/files/search?search_value=${codeText2}&format=json`;
                        var newWindow = window.open(url, '_blank'); // 在新标签页中打开URL
                        if (!newWindow) {
                            // 窗口可能被浏览器阻止了
                            alert('请允许浏览器打开新窗口或标签页。');
                        }
                    }
                });

                domainEle.appendChild(playBtn);
            }

            // // 增加video标签
            // let videoCon = domainEle.parentElement;
            // if (videoCon){
            //     let codeText2 = Data115.formatCode(codeText);
            //     let videoSrc = "https://fivetiu.com/" + codeText2.toLowerCase() + "/preview.mp4";
            //     let video = document.createElement('video');
            //     // video.style.display = "none";
            //     video.style = `
            //         position: absolute;
            //         left: 100px;
            //         height: 360px;
            //         display: none;
            //     `;
            //     video.autoplay = true;
            //     video.loop = true;
            //     video.muted = true;
            //     video.playsinline = true;
            //     video.dataset.src = videoSrc;
            //     // video.src =videoSrc;
            //
            //     videoCon.appendChild(video);
            // }

        }
    }

}

function addRightPanel(){

}

function addTopButton() {
    let hh = document.getElementsByClassName("header")[0];
    if (hh) {
        /* 读取按钮 */
        let changeTreeBtn = document.createElement("button");
        changeTreeBtn.class = "normalBtn";
        changeTreeBtn.textContent = "<<<"
        changeTreeBtn.addEventListener("click", function (event){
            let treeCon = document.getElementById('tree-container');
            let previewCon = document.getElementById('preview-con');

            if (changeTreeBtn.textContent === '<<<'){
                treeCon.style.width = '50px';
                previewCon.style.width = '1200px';

                changeTreeBtn.textContent = '>>>';
            }else {
                treeCon.style.width = '250px';
                previewCon.style.width = '1000px';

                changeTreeBtn.textContent = '<<<';
            }
        });

        /* 读取按钮 */
        let loadBtn = document.createElement("button");
        loadBtn.class = "normalBtn";
        loadBtn.textContent = "加载log"
        loadBtn.addEventListener("click", Logitem.logItemList);

        /* 读取按钮 */
        let loadSelBtn = document.createElement("button");
        loadSelBtn.class = "normalBtn";
        loadSelBtn.textContent = "选择的log"
        loadSelBtn.addEventListener("click", Logitem.logSelItem);

        /* 读取按钮 */
        let showImgBtn = document.createElement("button");
        showImgBtn.class = "normalBtn";
        showImgBtn.textContent = "列表按钮"
        showImgBtn.addEventListener("click", addItemListButton);

        /* 读取按钮 */
        let readFileListBtn = document.createElement("button");
        readFileListBtn.class = "normalBtn";
        readFileListBtn.textContent = "读取目录"
        readFileListBtn.addEventListener("click", PlayFlag.handleFolderSelection);

        /* 读取按钮 */
        let renameListBtn = document.createElement("button");
        renameListBtn.class = "normalBtn";
        renameListBtn.textContent = "去除115尾巴"
        renameListBtn.addEventListener("click", BookmarkTools.renameSelItem);
		
		/* 读取按钮 */
        let resetUrlBtn = document.createElement("button");
        resetUrlBtn.class = "normalBtn";
        resetUrlBtn.textContent = "更新bus网址"
        resetUrlBtn.addEventListener("click", BookmarkTools.resetUrlSelItem);

        hh.appendChild(changeTreeBtn);
        hh.appendChild(loadBtn);
        hh.appendChild(loadSelBtn);
        hh.appendChild(showImgBtn);
        hh.appendChild(readFileListBtn);
        hh.appendChild(renameListBtn);
		hh.appendChild(resetUrlBtn);
    }
}

function addImageWindow(){
    // 创建一个新的悬浮窗元素
    var floatingWindow = document.createElement('div');
    floatingWindow.id = "image-window"
    floatingWindow.className = 'floating-window';
    floatingWindow.style.width = '800px';
    floatingWindow.style.height = '540px';
    floatingWindow.style.position = 'fixed';
    floatingWindow.style.top = '50%';
    floatingWindow.style.left = '50%';
    floatingWindow.style.transform = 'translate(-50%, -50%)';
    floatingWindow.style.background = 'rgba(0, 0, 0, 0.6)';
    floatingWindow.style.color = 'white';
    floatingWindow.style.display = 'none';

// 创建一个新的图片元素
    var floatingImage = document.createElement('img');
    floatingImage.id = 'floatingImage';
    floatingImage.style.width = '100%';
    floatingImage.style.height = '100%';
    // floatingImage.src = "https://www.fanbus.cfd/pics/cover/7zdk_b.jpg";

// 创建一个新的关闭按钮元素
    var closeBtn = document.createElement('button');
    closeBtn.id = 'closeBtn';
    closeBtn.textContent = '关闭';
    closeBtn.style.position = 'absolute';
    closeBtn.style.top = '10px'; // 调整为合适的位置
    closeBtn.style.right = '10px'; // 调整为合适的位置
    closeBtn.addEventListener('click', function() {
        floatingWindow.style.display = 'none';
    });

// 将图片和关闭按钮添加到悬浮窗中
    floatingWindow.appendChild(floatingImage);
    floatingWindow.appendChild(closeBtn);

// 将悬浮窗添加到文档体中
    document.body.appendChild(floatingWindow);
}

function main(){
    // addPreloadImage();
    // addSelectEvent();
    // logItemList();

    addTopButton();
    // addRightPanel();
    addImageWindow();

    // 有跨域请求错误
    // Data115.search115Data("ipx-353", function (isRet, playAddr, pickcode, lookAddr, isRecord, isFavorite){
    //     if (isRet){
    //         alert('搜索115成功。');
    //     }
    // });
}

main();
